package org.zhengbo.imgUpload.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.zhengbo.imgUpload.model.CheckCode;
import org.zhengbo.imgUpload.model.ImgFile;
import org.zhengbo.imgUpload.model.MyException;

@Controller
public class MainController {

	final String PATH = "uploadFile";
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String index(HttpServletRequest request, Model mp) {
		String path = request.getSession().getServletContext().getRealPath(PATH);
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File[] imgFiles = dir.listFiles();
		List<ImgFile> imgs = new ArrayList<ImgFile>();
		for(int i = 0; i < imgFiles.length; i++) {
			ImgFile img = new ImgFile();
			img.setName(imgFiles[i].getName());
			img.setSize(imgFiles[i].length());
			img.setCreateTime(new Date(imgFiles[i].lastModified()));
			img.setUrl(request.getContextPath() + "/" + PATH + "/" + imgFiles[i].getName());
			imgs.add(img);
		}
		mp.addAttribute("imgs", imgs);
		return "list";
	}

	@RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username,HttpServletRequest request,
			@RequestParam("password") String password,@RequestParam("checkCode") String checkCode,Model m) {
		if(!checkCode.toUpperCase().equals(request.getSession().getAttribute("checkCode"))) {
			m.addAttribute("message", "您输入的验证码错误！");
			return "login";
		}else {
			// 验证用户密码
			if(username.equals("admin") && password.equals("admin")) {
				return "redirect:list";
			}else {
				m.addAttribute("message", "您输入的用户名或密码错误！");
				return "login";
			}
		}
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@RequestParam(value = "img", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		String path = request.getSession().getServletContext().getRealPath(PATH);
		if(file.isEmpty()) {
			throw new MyException("您还没有选择图片！");
		}
		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		if(!"jpg,jpeg,gif,bmp,png".contains(fileType)) {
			throw new MyException("您上传的文件不是图片！");
		}
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			throw new MyException("文件保存失败");
		}
		return "redirect:list";
	}
	
	@RequestMapping(value = "/delete")
	public String upload(@RequestParam(value = "img", required = false) String img,HttpServletRequest request) {
		String path = request.getSession().getServletContext().getRealPath(PATH);
		File targetFile = new File(path, img);
		try {
			targetFile.delete();
		} catch (Exception e) {
			throw new MyException("您要删除的文件不存在");
		}
		return "redirect:list";
	}
	
	@RequestMapping(value = "/checkCode", method = RequestMethod.GET)
	public void checkCode(HttpServletRequest request,HttpServletResponse response) {
		CheckCode cc = CheckCode.Instance();
		request.getSession().setAttribute("checkCode", cc.getCode());
		// 禁止图像缓存。  
        response.setHeader("Pragma", "no-cache"); 
        response.setHeader("Cache-Control", "no-cache"); 
        response.setDateHeader("Expires", 0); 
 
        response.setContentType("image/jpeg"); 
 
        try {
			// 将图像输出到Servlet输出流中。  
			ServletOutputStream sos = response.getOutputStream();
			ImageIO.write(cc.getBufferedImage(), "jpeg", sos);
			sos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
